package com.ccsoft.nio;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

// 使用一个 byteBuffer 实现拷贝一个文件
public class Ch04ChannelCopyFile {
    public static void main(String[] args) throws IOException {
        copy2();
    }

    // 设置适当小的缓冲区，循环读取数据
    public static void copy2() throws IOException {
        File src = new File("d:\\filechannel.txt");
        FileInputStream srcStream = new FileInputStream(src);
        FileChannel srcChannel = srcStream.getChannel();

        File dst = new File("d:\\02.txt");
        FileOutputStream dstStream = new FileOutputStream(dst);
        FileChannel dstChannel = dstStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        // 循环读取写入，知道读取到文件结束
        while(true){
            // 每次读取数据之前要清除标志属性
            // 否则导致 byteBuffer 中的 position = limit = 0
            // 会无限循环0执行下去
            byteBuffer.clear();
            int readLength = srcChannel.read(byteBuffer);
            if(readLength == -1) break;// 读取完毕则退出

            byteBuffer.flip();// 写数据之前要先反转
            dstChannel.write(byteBuffer);
        }

        srcStream.close();
        dstStream.close();
    }

    // 设置缓冲区为文件的大小，一次读取全部内容
    public static void copy1() throws IOException {
        File file = new File("d:\\filechannel.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        FileChannel readChannel = fileInputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());
        readChannel.read(byteBuffer);

        byteBuffer.flip();
        File target = new File("d:\\filechannel01.txt");
        FileOutputStream fileOutputStream = new FileOutputStream(target);
        FileChannel copyChannel = fileOutputStream.getChannel();
        copyChannel.write(byteBuffer);

        readChannel.close();
        copyChannel.close();
    }
}
